package demo4.controller;

import demo4.mapper.IUserMapper;
import demo4.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.Scanner;

@Component
public class UserController {
    @Autowired
    private IUserMapper userMapper;
    public void start(){
        System.out.println("用户系统");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要操作的序号");
        System.out.println("1.注册");
        System.out.println("2.登录");
        System.out.println("3.修改密码");
        System.out.println("4.用户列表");
        int num = scanner.nextInt();
        switch (num) {
            case 1:
//                System.out.println("注册");
                userReg();
                break;
            case 2:
               userLogin();
                break;
            case 3:
                System.out.println("修改密码");
                break;
            case 4:
                userList();
                break;

        }
    }
    //用户登录处理
    public void userLogin(){
        Scanner scanner=new Scanner(System.in);
        System.out.println("欢迎登录");
        System.out.println("请输入用户名");
        String username = scanner.nextLine();
        System.out.println("请输入密码");
        String password = scanner.nextLine();
        User user = userMapper.selectByUsername(username);
        if(user!=null){
            if(user.getPassword().equals(password)) {
                System.out.println("登录成功" + user.getNickname() + "回来");
            }else{
                System.out.println("密码不正确!");
            }
            }else{
            System.out.println("用户不存在!");
        }

        }


    private void userReg() {
        System.out.println("UserController:开始处理用户注册...");
        User user=new User();
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入用户名:");
            String username = scanner.nextLine();
            if(userMapper.selectByUsername( username)==null){
                user.setUsername(username);
                break;
            }
            System.out.println("用户名已存在");
        }
        System.out.println("请输入密码:");
        user.setPassword (scanner.nextLine());
        System.out.println("请输入昵称:");
        user.setNickname (scanner.nextLine());
        System.out.println("请输入年龄:");
        user.setAge(scanner.nextInt());
        int num=userMapper.insert(user);
        System.out.println(num>0?"注册成功":"注册失败");

        System.out.println("UserController:注册完毕");
    }
    public void userList(){
        System.out.println("用户列表");
        for(User user:userMapper.selectAll()){
            System.out.println(user);
        }
    }
}
